package com.linksfield.topup.utils;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 时间格式化输出工具类
 *
 * @author: lm
 * @date: 2020-03-31 10:00
 */
@Component
public class TimeFormatOutputUtil {

    private static Logger logger = Logger.getLogger(TimeFormatOutputUtil.class);

    /**
     * 获取当前日期
     * 格式：yyyy-MM-dd HH:mm:ss
     *
     * @return
     */
    public String currentDate() {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateNowStr = sdf.format(date);
        logger.info("此刻日期：" + dateNowStr);
        return dateNowStr;
    }

    /**
     * 获取当前日期
     * yyyy-MM-dd
     *
     * @return
     */
    public String currentDay() {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String dateNowStr = sdf.format(date);
        logger.info("今天日期：" + dateNowStr);
        return dateNowStr;
    }


    /**
     * 获取去年的年份：yyyy格式
     *
     * @return
     */
    public String lastYear() {
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        SimpleDateFormat laYears = new SimpleDateFormat("yyyy");
        c.add(Calendar.YEAR, -1);
        Date y = c.getTime();
        String lastYear = laYears.format(y);
        logger.info("去年：" + lastYear);
        return lastYear;
    }

    /***
     *获取当年的年份：yyyy格式
     * @return
     */
    public String currentYear() {
        SimpleDateFormat years = new SimpleDateFormat("yyyy");
        String currentYear = years.format(new Date());
        logger.info("本年：" + currentYear);
        return currentYear;
    }

    /***
     * 获取上月的年月份：yyyy-MM格式
     * @return
     */
    public String lastMonth() {
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
        c.add(Calendar.MONTH, -1);
        String lastMonth = format.format(c.getTime());
        logger.info("上月：" + lastMonth);
        return lastMonth;
    }

    /***
     * 获取当月的年月份：yyyy-MM格式
     * @return
     */
    public String currentMonth() {
        SimpleDateFormat months = new SimpleDateFormat("yyyy-MM");
        String currentMonth = months.format(new Date());
        logger.info("本月：" + currentMonth);
        return currentMonth;
    }

    /***
     * 本周开始第一天的日期：yyyy-MM-dd格式
     * 按照中国习惯，星期一作为一个星期的第一天。
     * @return
     */
    public String firstDayOfCurrentWeek() {
        String firstDayOfCurrentWeek;
        Calendar c = Calendar.getInstance();
        // 获得今天是一周的第几天，星期日是第一天，星期二是第二天，因为按中国礼拜一作为第一天所以这里减1
        int dayOfWeek = c.get(Calendar.DAY_OF_WEEK) - 1;
        int mondayPlus;
        if (dayOfWeek == 1) {
            mondayPlus = 0;
        } else {
            mondayPlus = 1 - dayOfWeek;
        }
        GregorianCalendar currentDate = new GregorianCalendar();
        currentDate.add(GregorianCalendar.DATE, mondayPlus);
        Date monday = currentDate.getTime();
        try {
            firstDayOfCurrentWeek = new SimpleDateFormat("yyyy-MM-dd").format(monday);
            logger.info("本周开始日期：" + firstDayOfCurrentWeek);
            return firstDayOfCurrentWeek;
        } catch (Exception e) {
            logger.info("时间转换有误");
        }
        return null;
    }

    /***
     * 本周结束最后一天的日期：yyyy-MM-dd格式
     * 按照中国习惯，星期天作为一个星期的最后一天。
     * @return
     */
    public String endDayOfCurrentWeek() {

        String endDayOfCurrentWeek;
        Calendar c = Calendar.getInstance();
        c.set(Calendar.DAY_OF_WEEK, c.getActualMaximum(Calendar.DAY_OF_WEEK));
        c.add(Calendar.DAY_OF_WEEK, 1);
        Date time = c.getTime();
        try {
            endDayOfCurrentWeek = new SimpleDateFormat("yyyy-MM-dd").format(time);
            logger.info("本周结束日期：" + endDayOfCurrentWeek);
            return endDayOfCurrentWeek;
        } catch (Exception e) {
            logger.info("时间转换有误");
        }
        return null;
    }


    /**
     * 上周开始第一天的日期：yyyy-MM-dd格式
     * 按照中国习惯，星期一作为一个星期的第一天。
     *
     * @return
     */
    public String firstDayOfLastWeek() {
        Calendar c = Calendar.getInstance();
        int firstDayOfWeek = c.get(Calendar.DAY_OF_WEEK) - 1;
        int offset = 1 - firstDayOfWeek;
        c.add(Calendar.DATE, offset - 7);
        String firstDayOfLastWeek = new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
        logger.info("上周开始日期：" + firstDayOfLastWeek);
        return firstDayOfLastWeek;
    }

    /***
     * 上周结束最后一天的日期：yyyy-MM-dd格式
     * 按照中国习惯，星期天作为一个星期的最后一天。
     * @return
     */
    public String endDayOfLastWeek() {
        Calendar c = Calendar.getInstance();
        int firstDayOfWeek = c.get(Calendar.DAY_OF_WEEK) - 1;
        int offset = 7 - firstDayOfWeek;
        c.add(Calendar.DATE, offset - 7);
        String endDayOfLastWeek = new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
        logger.info("上周结束日期：" + endDayOfLastWeek);
        return endDayOfLastWeek;
    }

    /**
     * 获取某月的第一天日期
     *
     * @param datadate
     * @return
     */
    public String getFirstDay(String datadate) {
        Date date = null;
        String day_first = null;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        try {
            date = format.parse(datadate);
        } catch (ParseException e) {
            logger.info("时间转换发生异常：" + e);
        }
        //创建日历
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        day_first = format.format(calendar.getTime());
        logger.info("某月第一天日期：" + day_first);
        return day_first;
    }

    /**
     * 获取某月的最后一天时间
     *
     * @param datadate
     * @return
     */
    public String getLastDay(String datadate) {
        Date date = null;
        String day_last = null;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        try {
            date = format.parse(datadate);
        } catch (ParseException e) {
            logger.info("时间转换发生异常：" + e);
        }
        //创建日历
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        //加一个月
        calendar.add(Calendar.MONTH, 1);
        //设置为该月第一天
        calendar.set(Calendar.DATE, 1);
        //再减一天即为上个月最后一天
        calendar.add(Calendar.DATE, -1);
        day_last = format.format(calendar.getTime());
        logger.info("某月最后一天日期：" + day_last);
        return day_last;
    }

    /**
     * JAVA获取某段时间内的所有日期
     *
     * @param dStart
     * @param dEnd
     * @return
     */
    public List<String> getDateBetween(String dStart, String dEnd) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<String> dateList = null;
        try {
            Calendar cStart = Calendar.getInstance();
            cStart.setTime(sdf.parse(dStart));
            dateList = new ArrayList<String>();
            //别忘了，把起始日期加上
            dateList.add(dStart);
            // 此日期是否在指定日期之后
            while (sdf.parse(dEnd).after(cStart.getTime())) {
                // 根据日历的规则，为给定的日历字段添加或减去指定的时间量
                cStart.add(Calendar.DAY_OF_MONTH, 1);
                dateList.add(sdf.format(cStart.getTime()));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        logger.info("某段时间内的日期列表：" + dateList);
        return dateList;
    }

    /**
     * 获取两个时间节点之间的月份列表
     *
     * @param minDate
     * @param maxDate
     * @return
     */
    public List<String> getMonthBetween(String minDate, String maxDate) {
        ArrayList<String> result = new ArrayList<String>();
        try {
            //格式化为年月
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");

            Calendar min = Calendar.getInstance();
            Calendar max = Calendar.getInstance();
            min.setTime(sdf.parse(minDate));
            min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);

            max.setTime(sdf.parse(maxDate));
            max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);

            Calendar curr = min;
            while (curr.before(max)) {
                result.add(sdf.format(curr.getTime()));
                curr.add(Calendar.MONTH, 1);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        logger.info("某段时间内的月份列表：" + result);
        return result;
    }

    /**
     * 判断当前数字是个几位数.
     * 通过一个数/10的次数来判断这个数字是个几位数
     *
     * @param num
     * @return
     */
    public static int LengthNum(int num) {
        //计数:
        int count = 0;
        while (num >= 1) {
            num /= 10;
            count++;
        }
        return count;
    }

    /**
     * 月份时间验证
     *
     * @param str
     * @return
     */
    public String monthFormat(String str) {
        try {
            Date date = new SimpleDateFormat("yyyy-MM").parse(str);
            logger.info("格式化到月份：" + new SimpleDateFormat("yyyy-MM").format(date));
            return "success";
        } catch (Exception e) {
            return "false";
        }
    }


    /**
     * 输出本周第一天的日期
     *
     * @return
     */
    public String firstDaysOfCurWeek() {
        String firstDay;
        Calendar curStartCal = Calendar.getInstance();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = (Calendar) curStartCal.clone();
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        firstDay = df.format(cal.getTime());
        System.out.println("本周周一:" + firstDay);
        return firstDay;
    }

    /**
     * 输出本周最后一天的日期
     *
     * @return
     */
    public String endDaysOfCurWeek() {
        String lastDay;
        Calendar curStartCal = Calendar.getInstance();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = (Calendar) curStartCal.clone();
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        cal.add(Calendar.DATE, 6);
        lastDay = df.format(cal.getTime());
        System.out.println("本周周天:" + lastDay);
        return lastDay;
    }

    /**
     * 获取本周是第几周
     *
     * @return
     * @throws ParseException
     */
    public String curWeek() {
        String curWeek;
        Calendar curStartCal = Calendar.getInstance();
        SimpleDateFormat dfWeek = new SimpleDateFormat("(第ww周)");
        Calendar cal = (Calendar) curStartCal.clone();
        curWeek = dfWeek.format(cal.getTime());
        System.out.println("本周是:" + curWeek);
        return curWeek;
    }

    /**
     * 本周第一天（周一）
     *
     * @return
     */
    public String first() {
        String firstDayOfLastWeek = "";
        try {
            Calendar c = Calendar.getInstance();
            // 默认时，每周第一天为星期日，需要更改一下
            c.setFirstDayOfWeek(Calendar.MONDAY);
            Date current = c.getTime();
            c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
            Date first = c.getTime();
            c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
            Date last = c.getTime();
            System.out.printf("当前日期：%tF%n", current);
            System.out.printf("本周第一天（周一）：%tF%n", first);
            firstDayOfLastWeek = new SimpleDateFormat("yyyy-MM-dd").format(first);
        } catch (Exception e) {
            logger.info("时间转换出现异常：" + e);
        }
        return firstDayOfLastWeek;
    }

    /**
     * 本周最后一天（周日）
     *
     * @return
     */
    public String last() {
        String endDayOfLastWeek = "";
        try {
            Calendar c = Calendar.getInstance();
            // 默认时，每周第一天为星期日，需要更改一下
            c.setFirstDayOfWeek(Calendar.MONDAY);
            Date current = c.getTime();
            c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
            Date first = c.getTime();
            c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
            Date last = c.getTime();
            endDayOfLastWeek = new SimpleDateFormat("yyyy-MM-dd").format(last);
            System.out.printf("本周最后一天（周日）：%tF%n", last);
        } catch (Exception e) {
            logger.info("时间转换出现异常：" + e);
        }
        return endDayOfLastWeek;
    }


    public static void main(String[] args) {
        Calendar c = Calendar.getInstance();
        // 默认时，每周第一天为星期日，需要更改一下
        c.setFirstDayOfWeek(Calendar.MONDAY);
        Date current = c.getTime();
        c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        Date first = c.getTime();
        c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
        Date last = c.getTime();
        System.out.printf("当前日期：%tF%n", current);
        System.out.printf("本周第一天（周一）：%tF%n", first);
        System.out.printf("本周最后一天（周日）：%tF%n", last);

    }


}
